package nuc.ss.wl.controller;

import nuc.ss.wl.entity.Student;
import nuc.ss.wl.service.StudentService;
import nuc.ss.wl.service.impl.StudentServiceImpl;
import nuc.ss.wl.utils.WebUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class StudentServlet extends BaseServlet {

    private StudentService studentService = new StudentServiceImpl();

    protected void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Student> studentList = studentService.findAll();
        request.setAttribute("studentList", studentList);
        request.getRequestDispatcher("/pages/manager/student_manager.jsp").forward(request, response);
    }

    protected void findStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 先完成回显数据
        int sno = WebUtil.parseInt(request.getParameter("sno"), 0);
        Student student = studentService.findBySno(sno);
        request.setAttribute("student", student);
        if (student != null) {
            request.getRequestDispatcher("/pages/manager/student_edit.jsp").forward(request, response);
        } else {

        }
    }

    protected void findStudentByClassno(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int classno = WebUtil.parseInt(request.getParameter("classno"), 0);
        Map<Float, Student> studentList = studentService.findStudentByClassno(classno);
        request.setAttribute("studentList", studentList);
        System.out.println(studentList);
        request.getRequestDispatcher("/pages/manager/student_class.jsp").forward(request, response);
    }

    protected void addStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Student student = WebUtil.populateParams(request.getParameterMap(), new Student());
        String realPassword = String.valueOf(student.getSno());
        String ssalt = UUID.randomUUID().toString();
        String spassword = WebUtil.encryptPassword(realPassword + ssalt);
        student.setSpassword(spassword);
        student.setSsalt(ssalt);
        studentService.add(student);
        response.sendRedirect(request.getContextPath() + "/studentServlet?action=findAll");
    }

    protected void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int sno = WebUtil.parseInt(request.getParameter("sno"), 0);
        studentService.delete(sno);
        response.sendRedirect(request.getContextPath() + "/studentServlet?action=findAll");
    }

    protected void updateStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Student updateStudent = WebUtil.populateParams(request.getParameterMap(), new Student());
        Student student= studentService.findBySno(updateStudent.getSno());
        System.out.println(updateStudent);
        System.out.println(student);
        student.setSname(updateStudent.getSname());
        student.setClassno(updateStudent.getClassno());
        student.setSsex(updateStudent.getSsex());
        student.setSage(updateStudent.getSage());
        student.setSphone(updateStudent.getSphone());
        studentService.update(student);
        response.sendRedirect(request.getContextPath() + "/studentServlet?action=findAll");
    }





    protected void exportXLS(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 调用业务层完成查询操作
        StudentService studentService = new StudentServiceImpl();
        List<Student> stuList = studentService.findAll();
        // 返回json字符串
        createExcel(stuList,response);
    }

    /**
     * 创建Excel
     * @param stuList
     *            数据
     */
    private static void createExcel( List<Student> stuList,HttpServletResponse response) {
        // 创建一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建一个工作表
        HSSFSheet sheet = workbook.createSheet("学生信息表1");
        CellRangeAddress region = new CellRangeAddress(0, // first row
                0, // last row
                0, // first column
                5 // last column
        );
        sheet.addMergedRegion(region);
        HSSFRow hssfRow = sheet.createRow(0);
        HSSFCell headCell = hssfRow.createCell(0);
        headCell.setCellValue("学生详细信息");
        // 设置单元格格式居中
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headCell.setCellStyle(cellStyle);

        // 添加表头行
        hssfRow = sheet.createRow(1);
        // 添加表头内容
        headCell = hssfRow.createCell(0);
        headCell.setCellValue("学号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(1);
        headCell.setCellValue("姓名");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(2);
        headCell.setCellValue("班号");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(3);
        headCell.setCellValue("性别");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(4);
        headCell.setCellValue("年龄");
        headCell.setCellStyle(cellStyle);

        headCell = hssfRow.createCell(5);
        headCell.setCellValue("手机号");
        headCell.setCellStyle(cellStyle);
        // 添加数据内容
        for (int i = 0; i < stuList.size(); i++) {
            hssfRow = sheet.createRow((int) i + 2);
            Student stu = stuList.get(i);

            // 创建单元格，并设置值
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(stu.getSno());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(1);
            cell.setCellValue(stu.getSname());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(2);
            cell.setCellValue(stu.getClassno());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(3);
            cell.setCellValue(stu.getSsex());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(4);
            cell.setCellValue(stu.getSage());
            cell.setCellStyle(cellStyle);

            cell = hssfRow.createCell(5);
            cell.setCellValue(stu.getSphone());
            cell.setCellStyle(cellStyle);
        }
        // 保存Excel文件
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment; fileName=student.xls" );//附件形式下载，文件名叫duty.xls
            //OutputStream outputStream = new FileOutputStream("D:/students.xls");  保存到了服务器端
            OutputStream outputStream = response.getOutputStream();//保存到客户端
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
